// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()//引用云数据库
const canJu = db.collection("canju")
const account = db.collection("account")

const _ = db.command
const $ = db.command.aggregate

const countPeople = (arr, key) => {
  return arr.reduce((acc, current) => {
    const value = current[key];
    if (!acc.set.has(value)) {
      acc.set.add(value);
      acc.count++;
    }
    return acc;
  }, { set: new Set(), count: 0 }).count;
}

const uniqueByOpenId = (arr, key) => {
  return arr.reduce((acc, item) => {
    if (!acc.some(i => i[key] === item[key])) {
      acc.push(item);
    }
    return acc;
  }, []);
}

// 云函数入口函数
// 残局函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let res = await canJu.aggregate()
    .match({ canPlay: true, win: false })
    .sample({ size: 5 })
    .project({ openid: 1, level: 1, progressTipsNum: 1, totalScoreRest: 1, playInfo: 1 })
    .lookup({
      from: 'account',
      let: { canJu_openid: '$openid' },
      pipeline: $.pipeline()
        .match(_.expr($.eq(['$openid', '$$canJu_openid'])))
        .project({ userInfo: 1 })
        .done(),
      as: 'userInfo'
    })
    .end()

  let arr = JSON.parse(JSON.stringify(res.list))

    for (let j = 0; j < arr.length; j++) {
      const item = arr[j];
      if (item.openid) { delete item.openid; }
    if (item.userInfo.length > 0) { item.userInfo = item.userInfo[0].userInfo }
    const alreadyPlay = item.playInfo.some(obj => obj.openid == wxContext.OPENID)
    item.alreadyPlay = alreadyPlay
    item.playInfo = uniqueByOpenId(item.playInfo, 'openid')
    item.countPeople = item.playInfo.length
    for (let i = 0; i < item.playInfo.length; i++) {
      const element = item.playInfo[i];
      let author = await account.where({
        openid: element.openid
      }).get()
      element.userInfo = author.data[0].userInfo
      element.userInfo.topCeng = author.data[0].topCeng + 1
    }
    }

  return arr

}
